<?php 
namespace App\Home\Controllers;
use Ratchet\MessageComponentInterface;
use Ratchet\ConnectionInterface;
  
class RatchetController implements MessageComponentInterface
{
    protected $clients;

    public function __construct()
    {
        $this->clients = new \SplObjectStorage;
    }

    public function onOpen(ConnectionInterface $conn)
    {
        $this->clients->attach($conn);
        echo "New connection\n";
    }

    public function onClose(ConnectionInterface $conn)
    {
        $this->clients->detach($conn);
        echo "Connection {$conn->resourceId} has disconnected\n";
    }

    public function onError(ConnectionInterface $conn, \Exception $e)
    {
        echo "An error has occurred: {$e->getMessage()}\n";
        $conn->close();
    }

    public function onMessage(ConnectionInterface $from, $msg)
    {
        // Decode the JSON message
        $data = json_decode($msg);
        // Send the message to all other clients
        foreach ($this->clients as $client) {
            if ($from !== $client) {
                $client->send(json_encode([
                    'type' => 'message',
                    'from' => $data->from,
                    'message' => $data->message,
                    'time' => date('Y-m-d H:i:s')
                ]));
            }
        }
    }
}
